<!--
 * @Author: zhuxiaoyi
 * @Date: 2024-01-09 10:50:36
 * @LastEditor: zhuxiaoyi
 * @LastEditTime: 2024-05-08 17:44:32
 * @Description: 
-->
<template>
    <el-row>
        <el-col :span="24" style="display: flex;justify-content:flex-end;position: relative;">
            <div style="position: absolute;z-index: 100;right: 0;top: 10px;">
                <el-card v-show="false" id="popup" class="ol-popup" style="width: 200px" shadow="always">
                    <template #header>
                        <div id="popup-header" class="popup-header">
                            <span>图斑编辑</span>
                            <el-button link class="button" @click="closeEditHandler" :icon="Close"></el-button>
                        </div>
                    </template>
                </el-card>
            </div>
        </el-col>
    </el-row>
    <div style="position: relative;">
        <el-card v-show="editBoard" style="max-width: 480px" class="edit-container">
            <div class="tool-body">
                <el-collapse-transition>
                    <el-card class="base-layer-card" size="small">
                        <template #header>
                            <div class="base-layer-header">
                                <span>底图选择</span>
                                <el-button link class="button" @click="popoverVisible = false" :icon="Close"></el-button>
                            </div>
                        </template>
                        <div class="base-layer-container">
                            <el-card v-for="layer in baseLayers" :key="layer.type" :body-style="{ padding: '0px' }"
                                style="width:74px;cursor: pointer;" class="img-card" @click="baseImageClickHandler(layer)">
                                <el-image style="width: 74px; height: 54px" :src="layer.img" :fit="'fill'" />
                                <div style="padding: 5px">
                                    <span>{{ layer.name }}</span>
                                </div>
                            </el-card>
                        </div>
                        <template #footer>
                            <el-row>
                                <el-col style="display: flex; justify-content:space-between">
                                    矢量图层
                                    <el-switch v-model="resultLayerVisible" @change="switchChangeHandler" />
                                </el-col>
                            </el-row>
                        </template>
                    </el-card>
                </el-collapse-transition>
            </div>
            <div>
            </div>
        </el-card>
    </div>
    <div id="map-container" :style="`height:${view.height}px`" @click="popoverVisible = false"></div>
    <div>
        <div id="mouse-position" class="position_coordinate"></div>
    </div>
</template>
<script setup lang="ts">
import { defineComponent, reactive, ref, toRefs, onMounted, watch } from "vue";
import axios from "axios";
import HttpService from "@/api/api";
import { Close, Edit } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter, useRoute } from "vue-router";
import { Map, View } from 'ol'
import { Style, Fill, Stroke } from 'ol/style'
import { Tile as TileLayer, Image } from 'ol/layer'
import { get, fromLonLat } from 'ol/proj';
import { getWidth, getTopLeft, boundingExtent } from 'ol/extent'
import { WMTS, TileWMS, OSM, Tile, ImageWMS, TileImage } from 'ol/source'
import MousePosition from "ol/control/MousePosition";
import { format as formatAxirs } from 'ol/coordinate';
import { WFS, GeoJSON } from 'ol/format';
import WMTSTileGrid from 'ol/tilegrid/WMTS'
import VectorSource from 'ol/source/Vector';
import VectorLayer from 'ol/layer/Vector';
import Select from 'ol/interaction/Select';
import Overlay from 'ol/Overlay.js';
import { singleClick, click } from 'ol/events/condition';
import Modify from 'ol/interaction/Modify';
import 'ol/ol.css'; // 导入 OpenLayers 样式文件
import baseImg1 from '@/assets/img/vec.jpg'
import baseImg2 from '@/assets/img/img.jpg'
import baseImg3 from '@/assets/img/ter.jpg'
var view = reactive({
    height: window.innerHeight,
});
const geoserverBaseURL = 'http://localhost:8055'
const resultLayerVisible = ref(true)
const popoverVisible = ref(false)
const router = useRouter()
const route = useRoute()
const projection = get("EPSG:4326");
const projectionExtent = projection.getExtent();
const size = getWidth(projectionExtent) / 256;
const resolutions = [];
const editBoard = ref(true);
const currentFeatureId = ref('')
// const currentShpName = ref('GF1D_PMS_E89.2_N31.9_20231228_L1A1257344264-MUX_ortho')
const currentShpName = ref('origin')
const editStatus = ref(false)
const classValue = ref('1')
var selectInteraction = null;
let runTimeParams: any = ref([])
const baseLayers = [
    {
        type: "vecLayer",
        name: "矢量底图",
        img: baseImg1
    },
    {
        type: 'imgLayer',
        name: "影像底图",
        img: baseImg2
    },
    {
        type: 'terLayer',
        name: "地形晕渲",
        img: baseImg3
    }
]

let map;
for (let z = 2; z < 19; ++z) {
    resolutions[z] = size / Math.pow(2, z);
}

let taskPagination = reactive({
    page_index: 1,
    page_size: 100,
    page_total: 301,
});
onMounted(() => {
    getAlgorithmParams()
   
});


const getAlgorithmParams = function () {
    let params = {
        graphId: route.query.graphId,
        id: route.params.id
    };
    
    HttpService.processListManage.getAlgorithmParams(
        params,
        (res) => {
            if (res.status == 200) {
                setTimeout(() => {
                    let currentParams = JSON.parse(res.data.data.runTimeParams)
                    let parsedParams = convertJsonArrayToObject(currentParams);
                    initMap(parsedParams.mapBox,parsedParams.shp_layer,parsedParams.tif_layer)
                }, 500)
            }
        },
        (error) => {

            console.log(error);
        }
    );
}

const convertJsonArrayToObject = function (jsonArray) {
    return jsonArray.reduce((result, item) => {
        result[item.param_name] = item.default_value;
        return result;
    }, {});
}
// 切换底图函数



const baseImageClickHandler = function (layer) {
    switchBaseLayer(layer.type)
}
const switchBaseLayer = (layerType) => {
    if (!map) return; // 如果地图对象不存在，则返回
    map.getLayers().forEach(layer => {
        if (layer.values_.name == layerType || layer.values_.name == 'imgLayer' || layer.values_.name == 'resultLayer' || layer.values_.name == 'baseLayer') {
            layer.setVisible(true)
        } else {
            layer.setVisible(false)
        }
    });
}
const switchChangeHandler = function () {
    changeLayerVisible('resultLayer', resultLayerVisible.value)
}
const changeLayerVisible = function (layerName, visible) {
    map && map.getLayers().forEach(layer => {
        if (layer.values_.name == layerName) {
            layer.setVisible(visible)
        }
    });
}

const initMap = function (mapBox,shp_layer,tif_layer) {
    const TIANDI_KEY = 'eec7fae87888db2dc4c30c0c458fb66b'
    const matrixSet = 'c'
    const wfsSource = new VectorSource({
        format: new GeoJSON(),
        url: function (extent) {
            return (
                geoserverBaseURL + '/geoserver/result/ows?service=WFS&' +
                `version=1.0.0&request=GetFeature&typeName=result:${currentShpName.value}_shp&` +
                'outputFormat=application/json&srsname=EPSG:4326&' +
                'bbox=' + extent.join(',') + ',EPSG:3857'
            );
        },
    });

    let vectorLayer = new VectorLayer({
        source: wfsSource,
        style: function (feature) {
            let classValue = feature.get('class');
            var color = '';
            if (classValue == '2') {
                // color = '#68A7C4';
                // color = '#ABC6EF';
                color = 'rgba(0, 0, 170, 0.6)';
            } else if (classValue == '1') {
                // color = '#EEEEEE';
                color = 'rgba(255, 255, 255,0)';
            } else {
                color = 'red'; // 默认颜色
            }
            return new Style({
                fill: new Fill({
                    color: color
                }),
            });
        }
    });
    vectorLayer.setOpacity(1);
    vectorLayer.set('name', "resultLayer")



    const shpLayer = new TileLayer({
        source: new TileWMS({
            url: geoserverBaseURL + '/geoserver/result/wms', // GeoServer的WMS服务URL
            params: {
                'LAYERS': 'result:' + shp_layer, // 要显示的图层的工作空间和名称,'FORMAT': 'image/png', // 图片格式
                'VERSION': '1.1.0',
                'FORMAT': 'image/png', // 图像格式为 PNG
            },
            serverType: 'geoserver'
        })
    })
    shpLayer.setOpacity(1);
    shpLayer.set('name', "resultLayer")

    const wmsLayers = new Image({
        source: new ImageWMS({
            url: geoserverBaseURL + '/geoserver/result/wms', // GeoServer的WMS服务URL
            params: {
                'LAYERS': 'result:' + tif_layer, // 要显示的图层的工作空间和名称,'FORMAT': 'image/png', // 图片格式
                'VERSION': '1.1.0',
                'FORMAT': 'image/png', // 图像格式为 PNG
                // 'FORMAT': 'image/jpeg', // 图像格式为 PNG
            },
            serverType: 'geoserver'
        })
    })
    wmsLayers.set('name', "baseLayer")
    wmsLayers.setOpacity(1);

    const terLayer = new TileLayer({
        source: new WMTS({
            url: `http://t{0-6}.tianditu.com/${'ter'}_${matrixSet}/wmts?tk=${TIANDI_KEY}`,
            layer: 'ter',
            matrixSet: matrixSet,
            style: "default",
            crossOrigin: 'anonymous', // 解决跨域问题 如无该需求可不添加
            format: "tiles",
            wrapX: true,
            tileGrid: new WMTSTileGrid({
                origin: getTopLeft(projectionExtent),
                //resolutions: res.slice(0, 15),
                resolutions: resolutions,
                matrixIds: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14']
            })
        })
    })
    terLayer.set('name', "terLayer")

    const imgLayer = new TileLayer({
        source: new WMTS({
            url: `http://t{0-6}.tianditu.com/${'img'}_${matrixSet}/wmts?tk=${TIANDI_KEY}`,
            layer: 'img',
            matrixSet: matrixSet,
            style: "default",
            crossOrigin: 'anonymous', // 解决跨域问题 如无该需求可不添加
            format: "tiles",
            wrapX: true,
            tileGrid: new WMTSTileGrid({
                origin: getTopLeft(projectionExtent),
                //resolutions: res.slice(0, 15),
                resolutions: resolutions,
                matrixIds: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14']
            })
        })
    })
    imgLayer.set('name', "imgLayer")

    const vecLayer = new TileLayer({
        source: new WMTS({
            url: `http://t{0-6}.tianditu.com/${'vec'}_${matrixSet}/wmts?tk=${TIANDI_KEY}`,
            layer: 'vec',
            matrixSet: matrixSet,
            style: "default",
            crossOrigin: 'anonymous', // 解决跨域问题 如无该需求可不添加
            format: "tiles",
            wrapX: true,
            tileGrid: new WMTSTileGrid({
                origin: getTopLeft(projectionExtent),
                //resolutions: res.slice(0, 15),
                resolutions: resolutions,
                matrixIds: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14']
            })
        })
    })

    vecLayer.set('name', "vecLayer")

    const cvaLayer = new TileLayer({
        source: new WMTS({
            url: `http://t{0-6}.tianditu.com/${'cva'}_${matrixSet}/wmts?tk=${TIANDI_KEY}`,
            layer: 'cva',
            matrixSet: matrixSet,
            style: "default",
            crossOrigin: 'anonymous', // 解决跨域问题 如无该需求可不添加
            format: "tiles",
            wrapX: true,
            tileGrid: new WMTSTileGrid({
                origin: getTopLeft(projectionExtent),
                resolutions: resolutions,
                matrixIds: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14']
            })
        })
    })
    cvaLayer.set('name', "cvaLayer")

    map = new Map({
        target: 'map-container',
        layers: [
            // 底图
            imgLayer,
            terLayer,
            vecLayer,
            cvaLayer,
            wmsLayers,
            // vectorLayer,
            shpLayer
        ],
        view: new View({
            projection: projection,
        })
    })

    // 创建一个包含四个角点的Extent对象

    map.getView().fit(mapBox, {
        constrainResolution: false // 可选，设置是否约束地图视图的分辨率
    });

    selectInteraction = new Select({
        condition: singleClick,
        style: function (feature) {
            // 自定义选中要素的样式，保留填充色
            let classValue = feature.get('class');
            var color = '';
            if (classValue == '2') {
                color = '#67c23a';
            } else if (classValue == '1') {
                color = '#CEEAD6';
            } else {
                color = 'rgba(255, 255, 255,0.1)'; // 默认颜色
            }
            return new Style({
                fill: new Fill({
                    color: color // 自定义填充色
                }),
                stroke: new Stroke({
                    color: '#529b2e', // 自定义边框颜色
                    width: 2 // 自定义边框宽度
                })
            });
        }
    });

    map.addInteraction(selectInteraction);

    var mousePositionControl = new MousePosition({
        coordinateFormat: function (coordinate) {
            return formatAxirs(coordinate, '经度:{x} 纬度:{y}', 2);
        },
        projection: 'EPSG:4326',
        className: "custom-mouse-position",
        target: document.getElementById("mouse-position"), //将位置数据放到那里
    });
    map.addControl(mousePositionControl);


    let modifyInteraction = new Modify({
        features: selectInteraction.getFeatures()
    });

    map.addInteraction(modifyInteraction);
    // 创建一个变量用于存储信息窗口对象的引用
    var popup = null;
    // 创建一个点击交互对象
    selectInteraction.on('select', function (event) {
        if (event.selected.length > 0) {
            // 处理选择的要素属性
            const selectedFeature = event.selected[0];
            currentFeatureId.value = selectedFeature['id_']
            let feature = selectedFeature.getProperties();
            classValue.value = feature.class.toString()
            if (editStatus.value) {
                // 获取鼠标位置
                var coordinate = event.mapBrowserEvent.coordinate;

                // 创建新的信息窗口对象
                popup = new Overlay({
                    element: document.getElementById('popup'),
                    positioning: 'bottom-center',
                    stopEvent: true,
                    offset: [0, -40]
                });

                // 将信息窗口添加到地图
                map.addOverlay(popup);

                // 显示信息窗口在鼠标位置
                popup.setPosition(coordinate);
                let popupElement = document.getElementById('popup');
                popupElement.style.display = 'block';
            }

        } else {
            closeEditHandler()
        }

    });

}

const closeEditHandler = function () {
    // 假设弹窗元素的ID为 "popup"
    var popupElement = document.getElementById('popup');
    popupElement.style.display = 'none';
    selectInteraction.getFeatures().clear();
}



const goBack = function () {
    router.push('/index/general/executeManage/executeList')
}
var view = reactive({
    height: window.innerHeight,
});

const formLabelAlign = reactive({
    name: '',
    region: '',
    type: '',
})

const pushReusltHandler = function (data) {
    console.log(data)
}


</script>
<style lang="scss" scoped>
#map-container {
    width: 100%;
    height: 600px;
    cursor: pointer;
}

.preview-card-header {
    display: flex;
    justify-content: space-between;
}

.base-layer-card {
    background: none;

    .base-layer-header {
        display: flex;
        justify-content: space-between;

    }

    .base-layer-container {
        display: flex;
        justify-content: space-between;
    }

    .img-card {
        border: 2px solid hsla(210, 96%, 54%, 0);

        &:hover {
            border: 2px solid #1989fa;
        }
    }
}

.task-card {
    z-index: 100;
    position: absolute;
    height: 680px;
    background: linear-gradient(0deg, #0b283b, rgba(21, 30, 40, 0.6));
    box-shadow: 0px 10px 19px 1px rgba(92, 99, 106, 0.38);
    border-radius: 3px;
    left: 34px;
    top: 120px;
    padding: 10px;

    .detial-con {
        padding: 10px;
        box-sizing: border-box;

        li {
            margin-bottom: 5px;
        }
    }

    overflow: scroll;
    overflow-x: hidden;
}

.custom-tree-node {
    width: 300px;

    .file-name {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
}

.position_coordinate {
    color: #fff;
    position: absolute;
    font-size: 14px;
    bottom: 20px;
    right: 20px;
    z-index: 999;
    text-align: center;
    line-height: 30px;
    background: linear-gradient(0deg, #0b283b, rgba(21, 30, 40, 0.6));
    padding: 5px 10px;
}
</style>
<style lang="scss">
.ol-popup {
    background: linear-gradient(0deg, #0b283b, rgba(21, 30, 40, 0.6));

    .el-card__header {
        padding: 5px !important;

        .popup-header {
            display: flex;
            justify-content: space-between;
            font-size: 12px;
        }
    }

    .el-card__body {
        padding: 10px;
    }
}

.map-popover {
    padding: 0;
}

.preview-card {
    .el-card__header {
        padding: 10px !important;
    }

    .el-card__body {
        padding: 0;
    }
}

.base-layer-card {
    .el-card__header {
        padding: 5px !important;
    }

    .el-card__body {
        padding: 15px;
    }

    .el-card__footer {
        padding: 5px !important;
    }
}

.task-card {
    .el-form-item {
        margin-bottom: 5px !important;
    }

    .filter-container {

        .el-input__wrapper {
            box-shadow: 0 0 0 1px rgb(109, 194, 236) inset;
            background: rgba(34, 42, 51, 0.5);
            color: #D1E5FF;
        }
    }

    .el-table {
        --el-table-header-bg-color: #1b384d9c !important;
        --el-table-tr-bg-color: #2a57779c !important;
        --el-table-border-color: rgb(109, 194, 236);
        --el-table-row-hover-bg-color: #152b3a9c !important;

        tr {
            cursor: pointer;
        }
    }

    .page-container {
        --el-input-border-color: rgb(109, 194, 236) !important;

        .el-input__wrapper {
            box-shadow: 0 0 0 1px rgb(109, 194, 236)inset;
        }

        .el-select {
            --el-select-border-color-hover: rgb(109, 194, 236) !important;
        }
    }


    .el-tree-node {
        .el-tree-node__content {
            height: 30px !important;
        }

        .is-current {
            background: #0b283b;
        }
    }

    .el-tree-node__content:hover {
        background-color: rgb(53, 113, 156) !important;
    }

    .el-tree {
        --el-tree-node-hover-bg-color: rgba(42, 87, 119, 1) !important;

        .el-tree-node__expand-icon {
            font-size: 20px;
            color: rgba(51, 147, 208, 1);
        }

    }


}

.edit-container {
    z-index: 100;
    position: absolute;
    background: linear-gradient(0deg, #0b283b, rgba(21, 30, 40, 0.6));
    box-shadow: 0px 10px 19px 1px rgba(92, 99, 106, 0.38);
    border-radius: 3px;
    right: 34px;
    top: 50px;
    width: 300px;

    .tool-header {
        padding: 0 5px 5px;
        border-bottom: 1px solid rgb(109, 194, 236);
        margin-bottom: 10px;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .tool-body {
        .el-avatar {
            margin-right: 10px;
        }
    }

    .tool-footer {
        padding: 10px 5px;
        border-top: 1px solid rgb(109, 194, 236);
        margin-top: 10px;
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .el-card__body {
        padding: 5px;

        .el-input__wrapper {
            box-shadow: 0 0 0 1px rgb(109, 194, 236) inset;
            background: rgba(34, 42, 51, 0.5);
            color: #D1E5FF;
        }
    }

}
</style>